package com.ruoyi.subsidy.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.subsidy.domain.AreaTreeVo;
import com.ruoyi.subsidy.domain.bo.SysSubsidyPlantingBo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.ruoyi.subsidy.domain.bo.SysStrativeAreaBo;
import com.ruoyi.subsidy.domain.vo.SysStrativeAreaVo;
import com.ruoyi.subsidy.domain.SysStrativeArea;
import com.ruoyi.subsidy.mapper.SysStrativeAreaMapper;
import com.ruoyi.subsidy.service.ISysStrativeAreaService;

import java.util.*;

/**
 * 行政区域Service业务层处理
 *
 * @author nbacheng
 * @date 2025-08-07
 */
@RequiredArgsConstructor
@Service
public class SysStrativeAreaServiceImpl implements ISysStrativeAreaService {

    private final SysStrativeAreaMapper baseMapper;

    /**
     * 查询行政区域
     */
    @Override
    public SysStrativeAreaVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    @Override
    public Integer queryTotolByTown(SysStrativeAreaBo bo){
        return baseMapper.queryTotolByTown(bo);
    }

    /**
     * 查询行政区域列表
     */
    @Override
    public TableDataInfo<SysStrativeAreaVo> queryPageList(SysStrativeAreaBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<SysStrativeArea> lqw = buildQueryWrapper(bo);
        Page<SysStrativeAreaVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }


    @Override
    public List<SysStrativeAreaVo> queryGroupedList(SysStrativeAreaBo bo) {
        LambdaQueryWrapper<SysStrativeArea> lqw = Wrappers.<SysStrativeArea>lambdaQuery()
            .groupBy(SysStrativeArea::getDepartmentName, SysStrativeArea::getTownName)
            .select(
                SysStrativeArea::getDepartmentName,
                SysStrativeArea::getTownName,
                // MySQL的GROUP_CONCAT，其他数据库需替换对应函数
                x -> "GROUP_CONCAT(village_name) as villageNames"
            );
        return baseMapper.selectVoList(lqw);
    }



    /**
     * 查询行政区域列表
     */
    @Override
    public List<SysStrativeAreaVo> queryList(SysStrativeAreaBo bo) {
        LambdaQueryWrapper<SysStrativeArea> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }


    @Override
    public List<AreaTreeVo> queryAreaTree(SysStrativeAreaBo bo) {
        // 1. 查询原始数据（带条件过滤）
        LambdaQueryWrapper<SysStrativeArea> lqw = Wrappers.lambdaQuery();

        if (StringUtils.isNotBlank(bo.getVillageName())) {
            lqw.eq(SysStrativeArea::getVillageName, bo.getVillageName());
        }
        if (StringUtils.isNotBlank(bo.getTownName())) {
            lqw.eq(SysStrativeArea::getTownName, bo.getTownName());
        }
        if (StringUtils.isNotBlank(bo.getDepartmentName())) {
            lqw.eq(SysStrativeArea::getDepartmentName, bo.getDepartmentName());
        }
       // lqw.eq(StringUtils.isNotBlank(bo.getStatus()), SysSubsidyPlantingBo::getStatus, bo.getStatus());

        List<SysStrativeArea> areas = baseMapper.selectList(lqw);
        Map<String, AreaTreeVo> districtMap = new LinkedHashMap<>();
        Map<String, AreaTreeVo> townMap = new HashMap<>();
        for (SysStrativeArea area : areas) {
            AreaTreeVo districtNode = districtMap.computeIfAbsent(
                area.getDepartmentName(),
                k -> new AreaTreeVo(area.getId(), area.getDepartmentName(), "district")
            );

            String townKey = area.getDepartmentName() + "|" + area.getTownName();
            AreaTreeVo townNode = townMap.computeIfAbsent(townKey, k -> {
                AreaTreeVo node = new AreaTreeVo(area.getId(), area.getTownName(), "town");
                districtNode.getChildren().add(node); // 已初始化，不会NPE
                return node;
            });
            townNode.getChildren().add(
                new AreaTreeVo(area.getId(), area.getVillageName(), "village")
            );
        }
        return new ArrayList<>(districtMap.values());
    }



    private LambdaQueryWrapper<SysStrativeArea> buildQueryWrapper(SysStrativeAreaBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<SysStrativeArea> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getVillageName()), SysStrativeArea::getVillageName, bo.getVillageName());
        lqw.like(StringUtils.isNotBlank(bo.getTownName()), SysStrativeArea::getTownName, bo.getTownName());
        lqw.like(StringUtils.isNotBlank(bo.getDepartmentName()), SysStrativeArea::getDepartmentName, bo.getDepartmentName());
        return lqw;
    }

    /**
     * 新增行政区域
     */
    @Override
    public Boolean insertByBo(SysStrativeAreaBo bo) {
        SysStrativeArea add = BeanUtil.toBean(bo, SysStrativeArea.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改行政区域
     */
    @Override
    public Boolean updateByBo(SysStrativeAreaBo bo) {
        SysStrativeArea update = BeanUtil.toBean(bo, SysStrativeArea.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(SysStrativeArea entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除行政区域
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }
}
